﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.IntroductionHospital;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.IntroductionHospital
{
    /// <summary>
    /// 医院简介命令处理器
    /// </summary>
    public class IntroductionHospitalHandler : IRequestHandler<IntroductionHospitalCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<IntroductionHospitalModel> baseRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="baseRepository">仓储</param>
        public IntroductionHospitalHandler(IMapper mapper, IBaseRepository<IntroductionHospitalModel> baseRepository)
        {
            this.mapper = mapper;
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">参数</param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(IntroductionHospitalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var dto = baseRepository.GetAll().Where(x => x.IntroductionHospitalId > 0).Count();
                if (dto == 0)
                {
                    var model = mapper.Map<IntroductionHospitalModel>(request);
                    model.IsDelete = false;
                    var entity = baseRepository.AddAsync(model).Result;
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = dto;
                }
                else
                {
                    request.IntroductionHospitalId = 1;
                    var xi = mapper.Map<IntroductionHospitalModel>(request);
                    xi.BriefIntroduction = request.BriefIntroduction;
                    await baseRepository.Update(xi);
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data = dto;
                }

                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
